# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
Desc    : Jenkins构建web端通知到飞书群
File    : feishu_rebot.py
author  : dragon
-------------------------------------------------------------------------------
"""

import requests
import sys
import time

JOB_NAME = sys.argv[1]
BUILD_NUMBER = sys.argv[2]
GIT_COMMIT_HASH = sys.argv[3]

# 构建时间
CURRENT_TIME = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# web端游戏地址
WEB_MOBILE_CLIENT_URL = "http://192.168.1.186:8080/game110/web-mobile/index.html"
WEB_MOBILE_EDITOR_CLIENT_URL = "http://192.168.1.186:8080/game110/web-mobile/index.html?edit=1"
# WEB_CLIENT_URL_MOBILE = "https://cos.wo117.com/tenlen/web/p1/web-mobile/index.html".format(PLATFORM)
# Jenkins构建web端机器人webhook
WEBHOOK_URL = (
    "https://open.feishu.cn/open-apis/bot/v2/hook/cc63e036-9952-4b92-9053-a58cf0b778a9"
)

# jenkins服务器地址
JENKINS_URL = "http://192.168.1.186:8090"


# 获取提交记录
def getCommitMsg(jobName, buildNumber):
    # 构建api的url
    apiUrl = f"{JENKINS_URL}/job/{jobName}/{buildNumber}/api/json"
    # 发起GET请求获取构建信息
    auth = ("admin", "q1w2e3r4t5")  # jenkins登录用户名和密码
    response = requests.get(apiUrl, auth=auth)
    retData = response.json()
    # 提取提交记录
    commitLog = ""
    if retData["changeSet"]["items"]:
        for c in retData["changeSet"]["items"]:
            print(c["msg"])
            if commitLog == "":
                commitLog = c["msg"]
            else:
                commitLog = commitLog + "\n" + c["msg"]
    if commitLog == "":
        commitLog = "本次没有发生变化"
    return commitLog


class SendNotice:
    def __init__(self):
        self.JOB_NAME = JOB_NAME  # 项目名称
        self.BUILD_NUMBER = BUILD_NUMBER  # 构建次数
        self.WEB_MOBILE_CLIENT_URL = WEB_MOBILE_CLIENT_URL  # web端的链接
        self.WEB_MOBILE_EDITOR_CLIENT_URL = WEB_MOBILE_EDITOR_CLIENT_URL
        self.WEBHOOK_URL = WEBHOOK_URL  # 飞书 webhook地址
        self.SCM_CHANGELOG = getCommitMsg(self.JOB_NAME, self.BUILD_NUMBER)

        title_extra = " (⛳️Game110) 构建报告 (开发版 🅰️)"
        self.method = "post"
        self.headers = {"Content-Type": "application/json"}
        self.json = {
            "msg_type": "interactive",
            "card": {
                "config": {"wide_screen_mode": True, "enable_forward": True},
                "elements": [
                    {
                        "tag": "div",
                        "text": {
                            "content": "构建名称：{}\n".format(self.JOB_NAME)
                            + "构建编号：{}\n".format(self.BUILD_NUMBER)
                            + "提交哈希：{}\n".format(GIT_COMMIT_HASH)
                            + "构建时间：{}\n".format(CURRENT_TIME)
                            + "变更记录：\n{}\n".format(self.SCM_CHANGELOG),
                            "tag": "lark_md",
                        },
                    },
                    {
                        "tag": "div",
                        "text": {"content": "<at id=all></at>", "tag": "lark_md"},
                    },
                    {
                        "actions": [
                            {
                                "tag": "button",
                                "text": {
                                    "content": "web-mobile",
                                    "tag": "lark_md",
                                },
                                "url": self.WEB_MOBILE_CLIENT_URL,
                                "type": "default",
                                "value": {},
                            },
                            {
                                "tag": "button",
                                "text": {
                                    "content": "web-mobile(Editor)",
                                    "tag": "lark_md",
                                },
                                "url": self.WEB_MOBILE_EDITOR_CLIENT_URL,
                                "type": "default",
                                "value": {},
                            },
                            {
                                "tag": "button",
                                "text": {
                                    "content": "Jenkins Job",
                                    "tag": "lark_md",
                                },
                                "url": f"{JENKINS_URL}/job/{self.JOB_NAME}/{self.BUILD_NUMBER}/",
                                "type": "primary",
                                "value": {},
                            },
                        ],
                        "tag": "action",
                    },
                ],
                "header": {
                    "title": {
                        "content": self.JOB_NAME + title_extra,
                        "tag": "plain_text",
                    }
                },
            },
        }

    def send_feishu(self):
        requests.request(
            method=self.method,
            url=self.WEBHOOK_URL,
            headers=self.headers,
            json=self.json,
        )


if __name__ == "__main__":
    SendNotice().send_feishu()
